/***
 * 
 */
layui.define(['layer', 'element'], function (exports) {
    var $ = layui.jquery;
    var layer = layui.layer;
    var element = layui.element;
    var setter = layui.cache;
    var headerDom = '.layui-layout-admin>.layui-header';
    var bodyDom = '.layui-layout-admin>.layui-body';
    var titleDom = bodyDom + '>.layui-body-header';
    var navFilter = 'admin-side-nav';
    var sideDom = '.layui-layout-admin>.layui-side>.layui-side-scroll';
    var tabDom = bodyDom + '>.layui-tab';
    var tabFilter = 'admintabs';
    var mIsAddTab = false;
    var mokui = { homeUrl: undefined, mTabPosition: undefined, mTabList: [] };
    var screen_size = { pc: [1025, -1], pad: [768, 1024], mobile: [0, 767] };

    //窗口大小
    var getDevice = function () {
        var width = $(window).width();
        for (var i in screen_size) {
            var sizes = screen_size[i],
                min = sizes[0],
                max = sizes[1];
            if (max == -1) max = width;
            if (min <= width && max >= width) {
                return i;
            }
        }
        return null;
    }

    var isDevice = function (label) {
        return getDevice() == label;
    }

    var isMobile = function () {
        if (isDevice('mobile') || isDevice('pad')) {
            return true;
        }
        return false;
    }

    /** 加载主页 */
    mokui.loadHome = function (param) {
        var cacheTabs = mokui.getTempData('indexTabs');// 获取缓存tab
        var cachePosition = mokui.getTempData('tabPosition');//当前tab位置
        var recover = (cacheTabs && cacheTabs.length > 0 && cacheTabs.length <= 10);
        mokui.homeUrl = param.url;
        param.noChange = cachePosition ? recover : false;
        //加载主页
        mokui.loadView(param);
        //如果有打开之前的一个窗口
        for (var i = 0; i < cacheTabs.length; i++) {
            if (cacheTabs[i].url == cachePosition) {
                mokui.loadView(cacheTabs[i]);
            }
        }
    };

    /** 加载页面 **/
    mokui.loadView = function (param) {
        if (!param.url) {
            layer.msg('url不能为空', { icon: 2, anim: 6 });
            return false;
        }
        var flag;  // 选项卡是否已添加
        $(tabDom + '>.layui-tab-title>li').each(function () {
            if ($(this).attr('lay-id') === param.url) {
                flag = true;
            }
        });
        if (!flag || flag == 'undefined') {
            // 添加选项卡
            mIsAddTab = true;
            element.tabAdd(tabFilter, {
                id: param.url, title: '<span class="title">' + (param.title || '') + '</span>',
                content: '<iframe class="admin-iframe" lay-id="' + param.url + '" src="' + param.url + '" onload="layui.mokui.hideLoading(this);" frameborder="0"></iframe>'
            });
            if (param.url !== mokui.homeUrl) {
                mokui.mTabList.push(param);  // 记录tab
            }
            mokui.putTempData('indexTabs', mokui.mTabList);  // 缓存tab
        }
        element.tabChange(tabFilter, param.url);  // 切换到此tab
        if (mokui.getPageWidth() <= 768) {
            mokui.flexible(true);
        }
    };

    mokui.parseJSON = function (str) {
        if (typeof str === 'string') {
            try {
                return JSON.parse(str);
            } catch (e) {
            }
        }
        return str;
    };

    /** 打开tab */
    mokui.openTab = function (param) {
        if (window !== top && top.layui && top.layui.index) {
            return top.layui.mokui.openTab(param);
        }
        mokui.loadView({ url: param.url, title: param.title });
    };

    /** 关闭tab */
    mokui.closeTab = function (url) {
        if (window !== top && top.layui && top.layui.index) {
            return top.layui.mokui.closeTab(url);
        }
        element.tabDelete(tabFilter, url);
    };

    /** 设置是否记忆Tab */
    mokui.setTabCache = function (isCache) {
        if (window !== top && top.layui && top.layui.index) {
            return top.layui.mokui.setTabCache(isCache);
        }
        mokui.putSetting('cacheTab', isCache);
        if (!isCache) {
            return mokui.clearTabCache();
        }
        mokui.putTempData('indexTabs', mokui.mTabList);
        mokui.putTempData('tabPosition', mokui.mTabPosition);
    };

    /** 清除tab记忆 */
    mokui.clearTabCache = function () {
        mokui.putTempData('indexTabs', null);
        mokui.putTempData('tabPosition', null);
    };

    /** 设置tab标题 */
    mokui.setTabTitle = function (title, tabId) {
        if (window !== top && top.layui && top.layui.index) return top.layui.mokui.setTabTitle(title, tabId);
        if (setter.pageTabs) {
            if (!tabId) tabId = $(tabDom + '>.layui-tab-title>li.layui-this').attr('lay-id');
            if (tabId) $(tabDom + '>.layui-tab-title>li[lay-id="' + tabId + '"] .title').html(title || '');
        } else if (title) {
            $(titleDom + '>.layui-body-header-title').html(title);
            $(titleDom).addClass('show');
            $(headerDom).css('box-shadow', '0 1px 0 0 rgba(0, 0, 0, .03)');
        } else {
            $(titleDom).removeClass('show');
            $(headerDom).css('box-shadow', '');
        }
    };

    /** 滑动选项卡 */
    mokui.rollPage = function (d) {
        if (window !== top && top.layui && top.layui.mokui) return top.layui.mokui.rollPage(d);
        var $tabTitle = $(tabDom + '>.layui-tab-title');
        var left = $tabTitle.scrollLeft();
        if ('left' === d) {
            $tabTitle.animate({ 'scrollLeft': left - 120 }, 100);
        } else if ('auto' === d) {
            var autoLeft = 0;
            $tabTitle.children("li").each(function () {
                if ($(this).hasClass('layui-this')) {
                    return false;
                } else {
                    autoLeft += $(this).outerWidth();
                }
            });
            $tabTitle.animate({ 'scrollLeft': autoLeft - 120 }, 100);
        } else {
            $tabTitle.animate({ 'scrollLeft': left + 120 }, 100);
        }
    };

    /** 让当前的iframe弹层自适应高度 **/
    mokui.iframeAuto = function () {
        return parent.layer.iframeAuto(parent.layer.getFrameIndex(window.name));
    };

    /** 获取浏览器高度 **/
    mokui.getPageHeight = function () {
        return document.documentElement.clientHeight || document.body.clientHeight;
    };

    /** 获取浏览器宽度 **/
    mokui.getPageWidth = function () {
        return document.documentElement.clientWidth || document.body.clientWidth;
    };

    /** 自定义tab标题 **/
    mokui.setTabTitleHtml = function (html) {
        if (window !== top && top.layui && top.layui.index) return top.layui.mokui.setTabTitleHtml(html);
        if (setter.pageTabs) return;
        if (!html) return $(titleDom).removeClass('show');
        $(titleDom).html(html);
        $(titleDom).addClass('show');
    };

    /** 关闭loading */
    mokui.hideLoading = function (url) {
        if (typeof url !== 'string') url = $(url).attr('lay-id');
    };

    /** 折叠时罩层 **/
    var siteShadeDom = '.layui-layout-admin .site-mobile-shade';
    if ($(siteShadeDom).length === 0) {
        $('.layui-layout-admin').append('<div class="site-mobile-shade"></div>');
    }
    $(siteShadeDom).click(function () {
        mokui.flexible(true);
    });



    /** 设置侧栏折叠 **/
    // $('.slide-sidebar').on('click', function () {
    //     mokui.strToWin($(this).data('window')).layui.mokui.flexible();
    // })
    mokui.slideSideBar = function () {

        var $slideSidebar = $('.slide-sidebar'),
            $pageContainer = $('.layui-body'),
            $mobileMask = $('.mobile-mask');

        var isFold = false;

        if (isMobile()) {
            // $(".slide-sidebar i").removeClass('layui-icon-spread-right').addClass('layui-icon-spread-left');
            $admin = $('body').find('.layui-layout-admin');
            // $admin.addClass('fold-side-bar-xs');
            $admin.addClass('admin-nav-mini');
            isFold = true;
            $mobileMask.click(function () {
                $slideSidebar.trigger('click');
            });
        }

        $slideSidebar.click(function (e) {
            e.preventDefault();

            var $this = $(this),
                $icon = $this.find('i'),
                $admin = $('body').find('.layui-layout-admin');
            var toggleClass = isMobile() ? 'fold-side-bar-xs' : 'fold-side-bar';//fold-side-bar-xs

            if ($icon.hasClass('layui-icon-spread-right')) {
                $icon.removeClass('layui-icon-spread-right').addClass('layui-icon-spread-left');
                $admin.addClass(toggleClass);
                $admin.addClass('admin-nav-mini');
                isFold = true;
                if (isMobile()) $mobileMask.show();
            } else {
                $icon.removeClass('layui-icon-spread-left').addClass('layui-icon-spread-right');
                $admin.removeClass(toggleClass);
                $admin.removeClass('admin-nav-mini');
                isFold = false;
                if (isMobile()) $mobileMask.hide();
            }
        });
    }

    mokui.slideSideBar();
    mokui.flexible = function (expand) {
        if (window !== top && top.layui && top.layui.mokui) return top.layui.mokui.flexible(expand);
        var $layout = $('.layui-layout-admin');
        var isExapnd = $layout.hasClass('admin-nav-mini');
        if (expand === undefined) expand = isExapnd;
        if (isExapnd === expand) {
            if (window.sideFlexTimer) clearTimeout(window.sideFlexTimer);
            $layout.addClass('admin-side-flexible');
            window.sideFlexTimer = setTimeout(function () {
                $layout.removeClass('admin-side-flexible');
            }, 600);
            if (expand) {
                $layout.removeClass('admin-nav-mini');
            } else {
                $layout.addClass('admin-nav-mini');
            }
        }
    };

    /** 侧导航折叠状态下鼠标经过右侧展现下级菜单 **/
    var navItemDom = '.layui-layout-admin.admin-nav-mini.fold-side-bar>.layui-side .layui-nav .layui-nav-item';
    $(document).on('mouseenter', navItemDom + ',' + navItemDom + ' .layui-nav-child>dd', function () {
        if (mokui.getPageWidth() > 768) {
            var $that = $(this), $navChild = $that.find('>.layui-nav-child');
            if ($navChild.length > 0) {
                $that.addClass('admin-nav-hover');
                $navChild.css('left', $that.offset().left + $that.outerWidth());
                var top = $that.offset().top;
                if (top + $navChild.outerHeight() > mokui.getPageHeight()) {
                    top = top - $navChild.outerHeight() + $that.outerHeight();
                    if (top < 60) top = 60;
                    $navChild.addClass('show-top');
                }
                $navChild.css('top', top);
            } else if ($that.hasClass('layui-nav-item')) {
                mokui.tips({ elem: $that, text: $that.find('a').text(), direction: 2, offset: '12px' });
            }
        }
    }).on('mouseleave', navItemDom + ',' + navItemDom + ' .layui-nav-child>dd', function () {
        layer.closeAll('tips');
        var $this = $(this);
        $this.removeClass('admin-nav-hover');
        var $child = $this.find('>.layui-nav-child');
        $child.css({ 'left': 'auto', 'top': 'auto' });
    });

    /** 监听预定义mokui-event **/
    $(document).on('click', '*[mokui-event]', function () {
        var te = mokui.events[$(this).attr('mokui-event')];
        te && te.call(this, $(this));
    });

    /** 侧导航点击监听 */
    element.on('nav(' + navFilter + ')', function (elem) {
        var $that = $(elem);
        var href = $that.attr('data-url');
        if (!href || href === '#') return;
        if (href.indexOf('javascript:') === 0) {
            return new Function(href.substring(11))();
        }
        var name = $that.attr('mokui-title') || $that.text().replace(/(^\s*)|(\s*$)/g, '');
        var end = $that.attr('mokui-end');
        try {
            if (end) end = new Function(end);
            else end = undefined;
        } catch (e) {
            console.error(e);
        }
        mokui.openTab({ url: href, title: name, end: end });
        layui.event.call(this, 'admin', 'side({*})', { href: href });
    });

    /** 字符串形式的parent.parent转window对象 */
    mokui.strToWin = function (str) {
        var win = window;
        if (!str) return win;
        var ws = str.split('.');
        for (var i = 0; i < ws.length; i++) win = win[ws[i]];
        return win;
    };

    /** 所有mokui-href处理 */
    $(document).on('click', '*[mokui-href]', function () {
        var $this = $(this);
        var href = $this.attr('mokui-href');
        if (!href || href === '#') {
            return false;
        };
        if (href.indexOf('javascript:') === 0) return new Function(href.substring(11))();
        var title = $this.attr('mokui-title') || $this.text();
        var win = $this.data('window');
        win ? (win = mokui.strToWin(win)) : (win = top);
        var end = $this.attr('mokui-end');
        try {
            if (end) end = new Function(end);
            else end = undefined;
        } catch (e) {
            console.error(e);
        }
        if (win.layui && win.layui.index) win.layui.mokui.openTab({ title: title || '', url: href, end: end });
        else location.href = href;
    });

    /** tab切换监听 */
    element.on('tab(' + tabFilter + ')', function () {
        var layId = $(this).attr('lay-id');
        mokui.mTabPosition = (layId !== mokui.homeUrl ? layId : undefined);// 记录当前Tab位置
        mokui.putTempData('tabPosition', mokui.mTabPosition);
        mokui.activeNav(layId);
        mokui.rollPage('auto');
        mokui.refresh(layId, true);
    });

    /** tab删除监听 */
    element.on('tabDelete(' + tabFilter + ')', function (data) {
        var mTab = mokui.mTabList[data.index - 1];
        if (mTab) {
            mokui.mTabList.splice(data.index - 1, 1);
            mokui.putTempData('indexTabs', mokui.mTabList);
            layui.event.call(this, 'admin', 'tabDelete({*})', { layId: mTab.url });
        }
        if ($(tabDom + '>.layui-tab-title>li.layui-this').length === 0) {
            $(tabDom + '>.layui-tab-title>li:last').trigger('click');
        }
    });

    /** layui缓存临时数据 **/
    mokui.putTempData = function (key, value, local) {
        var tableName = local ? setter.tableName : setter.tableName + '_tempData';
        if (value === undefined || value === null) {
            if (local) layui.data(tableName, { key: key, remove: true });
            else layui.sessionData(tableName, { key: key, remove: true });
        } else {
            if (local) layui.data(tableName, { key: key, value: value });
            else layui.sessionData(tableName, { key: key, value: value });
        }
    };

    /** layui获取缓存临时数据 **/
    mokui.getTempData = function (key, local) {
        if (typeof key === 'boolean') {
            local = key;
            key = undefined;
        }
        var tableName = local ? setter.tableName : setter.tableName + '_tempData';
        var tempData = local ? layui.data(tableName) : layui.sessionData(tableName);
        if (!key) return tempData;
        return tempData ? tempData[key] : undefined;
    };

    /** 修改配置信息 **/
    mokui.putSetting = function (key, value) {
        setter[key] = value;
        putTempData(key, value, true);
    };


    /** 导航栏选中处理 **/
    mokui.activeNav = function (url) {
        $(sideDom + '>.layui-nav .layui-nav-item .layui-nav-child dd.layui-this').removeClass('layui-this');
        $(sideDom + '>.layui-nav .layui-nav-item.layui-this').removeClass('layui-this');

        var $a = $(sideDom + '>.layui-nav a[data-url="' + url + '"]');
        if ($a.length === 0) return console.warn(url + ' not found');
        var isMini = $('.layui-layout-admin').hasClass('fold-side-bar');

        var $pChilds = $a.parent('dd').parents('.layui-nav-child');
        $(sideDom + '>.layui-nav .layui-nav-itemed').not($pChilds.parent()).removeClass('layui-nav-itemed');

        $a.parent().addClass('layui-this');  // 选中当前
        // 展开所有父级
        var $asParents = $a.parent('dd').parents('.layui-nav-child').parent();
        if (!isMini) {
            var $childs = $asParents.not('.layui-nav-itemed').children('.layui-nav-child');
        }
        $asParents.addClass('layui-nav-itemed');
    };

    window.getPageHeight = function () {
        return document.documentElement.clientHeight || document.body.clientHeight;
    };

    /** 刷新当前选项卡 **/
    mokui.refresh = function (url, isIndex) {
        if (window !== top && top.layui && top.layui.mokui) return top.layui.mokui.refresh(url);
        var $iframe;
        if (!url) {
            $iframe = $(tabDom + '>.layui-tab-content>.layui-tab-item.layui-show>.admin-iframe');
            if (!$iframe || $iframe.length <= 0) $iframe = $(bodyDom + '>div>.admin-iframe');
        } else {
            $iframe = $(tabDom + '>.layui-tab-content>.layui-tab-item>.admin-iframe[lay-id="' + url + '"]');
            if (!$iframe || $iframe.length <= 0) $iframe = $(bodyDom + '>.admin-iframe');
        }
        if (!$iframe || !$iframe[0]) return console.warn(url + ' is not found');
        try {
            if (isIndex && $iframe[0].contentWindow.refreshTab) {
                $iframe[0].contentWindow.refreshTab();
            } else {
                // strToWin.showLoading({elem: $iframe.parent(), size: ''});
                $iframe[0].contentWindow.location.reload();
            }
        } catch (e) {
            console.warn(e);
            $iframe.attr('src', $iframe.attr('src'));
        }
    };

    /** 关闭当前选项卡 **/
    mokui.closeThisTabs = function (url) {
        if (window !== top && top.layui && top.layui.mokui) {
            return top.layui.mokui.closeThisTabs(url);
        }
        mokui.closeTabOperNav();
        var $title = $(tabDom + '>.layui-tab-title');
        if (!url) {
            if ($title.find('li').first().hasClass('layui-this')) {
                return layer.msg('主页不能关闭', { icon: 2 });
            }
            $title.find('li.layui-this').find('.layui-tab-close').trigger('click');
        } else {
            if (url === $title.find('li').first().attr('lay-id')) {
                return layer.msg('主页不能关闭', { icon: 2 });
            }
            $title.find('li[lay-id="' + url + '"]').find('.layui-tab-close').trigger('click');
        }
    };

    /** 关闭其他选项卡 **/
    mokui.closeOtherTabs = function (url) {
        if (window !== top && top.layui && top.layui.mokui) return top.layui.mokui.closeOtherTabs(url);
        if (!url) {
            $(tabDom + '>.layui-tab-title li:gt(0):not(.layui-this)').find('.layui-tab-close').trigger('click');
        } else {
            $(tabDom + '>.layui-tab-title li:gt(0)').each(function () {
                if (url !== $(this).attr('lay-id')) $(this).find('.layui-tab-close').trigger('click');
            });
        }
        mokui.closeTabOperNav();
    };

    /** 关闭所有选项卡 **/
    mokui.closeAllTabs = function () {
        if (window !== top && top.layui && top.layui.mokui) return top.layui.mokui.closeAllTabs();
        $(tabDom + '>.layui-tab-title li:gt(0)').find('.layui-tab-close').trigger('click');
        $(tabDom + '>.layui-tab-title li:eq(0)').trigger('click');
        mokui.closeTabOperNav();
    };

    /** 关闭选项卡操作菜单 **/
    mokui.closeTabOperNav = function () {
        if (window !== top && top.layui && top.layui.mokui) {
            return top.layui.mokui.closeTabOperNav();
        }
        $('.layui-icon-down .layui-nav .layui-nav-child').removeClass('layui-show');
    };

    /** 选项卡操作 **/
    $(document).on('click', ".taboption dd", function () {
        var type = $(this).attr("data-type");
        var layId = $(tabDom).find('#appTabs li.layui-this').attr('layui-id');
        switch (type) {
            case 'current':
                mokui.closeThisTabs(layId);
                break;
            case 'all':
                mokui.closeAllTabs();
                break;
            case 'fresh':
                element.tabChange(tabFilter, layId);
                mokui.refresh(layId);
                break;
            case 'other':
                mokui.closeOtherTabs(layId);
                break;
        }
        $(this).parent().removeClass('layui-show');
    });

    $(document).on('click','.freshThis',function(){
        var layId = $(tabDom).find('#appTabs li.layui-this').attr('layui-id');
        mokui.refresh(layId);
    })

    //全屏
    mokui.fullscreen = function () {
        if (document.fullscreenElement ||
            document.mozFullScreenElement ||
            document.webkitFullscreenElement ||
            document.msFullscreenElement) {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
                document.msExitFullscreen();
            }
        } else {
            if (document.documentElement.requestFullscreen) {
                document.documentElement.requestFullscreen();
            } else if (document.documentElement.mozRequestFullScreen) {
                document.documentElement.mozRequestFullScreen();
            } else if (document.documentElement.webkitRequestFullscreen) {
                document.documentElement.webkitRequestFullscreen();
            } else if (document.documentElement.body.msRequestFullscreen) {
                document.documentElement.body.msRequestFullscreen();
            }
        }
    }
    $(".fullscreen").on("click", function () {
        if ($(this).find('a>i').hasClass('layui-icon-screen-full')) {
            $(this).find('a>i').removeClass('ayui-icon-screen-full').addClass('layui-icon-screen-restore');
        } else {
            $(this).find('a>i').removeClass('layui-icon-screen-restore').addClass('ayui-icon-screen-full');
        }
        mokui.fullscreen();
    });

    //在父层弹出
    mokui.openUri = function (title, url, width, height, btns, callback) {
        var mokindex = layer.open({
            type: 2,
            maxmin: true,
            area: [width ? width : 'auto', height ? height : 'auto'],
            title: title || '弹窗',
            content: url,
            btn: btns,
            btnAlign: 'c',
            skin: 'layui-layer-molv',
            success: function (layero, index) { },
            yes: function (mokindex, layero) {
                callback && callback('1', mokindex, layero);
            },
            btn1: function (mokindex, layero) {
                callback && callback('2', mokindex, layero);
            }
        })
    }


    //当前页面弹出
    window.openUri = function (title, url, width, height, btns, callback) {

        var mokindex = layer.open({
            type: 2,
            maxmin: true,
            area: [width ? width : 'auto', height ? height : 'auto'],
            title: title || '弹窗',
            content: url,
            btn: btns,
            btnAlign: 'c',
            skin: 'layui-layer-molv',
            success: function (layero, index) { },
            yes: function (mokindex, layero) {
                callback && callback('1', mokindex, layero);
            },
            btn1: function (mokindex, layero) {
                callback && callback('2', mokindex, layero);
            }
        })

    }

    //兼容性
    if (layui.device().ios) {
        $('body').addClass('ios-iframe-body');
    }

    exports('mokui', mokui);
});
